package com.mk.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import org.apache.ibatis.session.SqlSession;

import com.mk.web.util.MybatisUtil;

/**
 * 使用servlet filter方式代理SqlSession产生过程
 * Created by WangChen on 2018/11/27 16:40.
 */
@WebFilter("/*")
public class OpenSessionInViewFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        SqlSession sqlSession = MybatisUtil.getSession();

        try {
            chain.doFilter(request, response);
            sqlSession.commit();
        }catch (Exception e){
            sqlSession.rollback();
        }finally {
            MybatisUtil.closeSession();
        }

    }

    @Override
    public void destroy() {

    }
}
